package com.ai.notices.web.system.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ai.notices.dao.mysql.model.AuthStaff;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ai.notices.web.system.util.StaffSessionUtil;

/**
 * 是否登录省份验证
 * 
 * @author lixc
 *
 */
public class LoginFilter implements Filter {

	public String loginPage = "/login";// 在web.xml中配置
	public String mainPage = "/main/pageInit";// 在web.xml中配置

	public static final String sessionOutPage = "/system/sessionOut"; // 写死在这，因为不会再修改
	public static final String noAuthPage = "/system/noAuth";// 写死在这，因为不会再修改

	public String[] IGNORE_SUFFIX = {};// 在web.xml中配置

	public Object[] NOTLOGIN_PAGES = {};// 在web.xml中配置
	public Object[] NEEDLOGIN_PAGES = {};// 在web.xml中配置

	private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession();
		
		String uri = request.getServletPath();
		
		// 过滤不需要权限控制的Url
		if (shouldFilter(request) == false) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}

		if (uri.endsWith(this.loginPage)) {
			filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if(uri.indexOf("/login/check")!=-1){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

		//没有登录时需要先登录
        AuthStaff staff = StaffSessionUtil.getStaffInfo(session);
		if(null == staff){
			response.sendRedirect(request.getContextPath() + loginPage);
			return;
		}

//        if(staff == null){
//
//            staff = new StaffInfoVo();
//            staff.setUserId("admin");
//            staff.setUserName("超级管理员");
//            ClassPathResource resource = new ClassPathResource("/devMenu.json", LoginFilter.class);
//            List<MenuDisplayVO> menus = new ObjectMapper().readValue(resource.getInputStream(),new TypeReference<List<MenuDisplayVO>>(){});
//
//            processMenus(menus,staff,session);
//
//            // 设置登陆信息
//            StaffSessionUtil.setStaffInfo(session, staff);
//        }
        
//        if (uri.endsWith(this.loginPage)) {
//            response.sendRedirect(request.getContextPath() + loginPage);
//            return;
//        }
        
        filterChain.doFilter(servletRequest, servletResponse);
        return;
		
	}


	/**
	 * 过滤指定后缀文件不走Filter
	 * 
	 * @param request
	 * @return
	 */
	private boolean shouldFilter(HttpServletRequest request) {
		String uri = request.getRequestURI().toLowerCase();

		for (String suffix : IGNORE_SUFFIX) {
			if (uri.endsWith(suffix)) {
				return false;
			}
		}

		return true;
	}


	/**
	 * web容器初始化
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		String loginPage = config.getInitParameter("loginPage");
		if (StringUtils.isNotBlank(loginPage)) {
			this.loginPage = loginPage;
		}

		String mainPage = config.getInitParameter("mainPage");
		if (StringUtils.isNotBlank(mainPage)) {
			this.mainPage = mainPage;
		}

		String ignore_suffix = config.getInitParameter("ignore_suffix");
		if (StringUtils.isEmpty(ignore_suffix) == false)
			IGNORE_SUFFIX = ignore_suffix.split(",");

		String notlogin_pages = config.getInitParameter("notlogin_pages");
		if (StringUtils.isEmpty(notlogin_pages) == false)
			NOTLOGIN_PAGES = notlogin_pages.split(",");

		String needlogin_pages = config.getInitParameter("needlogin_pages");
		if (StringUtils.isEmpty(needlogin_pages) == false)
			NEEDLOGIN_PAGES = needlogin_pages.split(",");

	}

	/**
	 * 判断是否是Ajax请求
	 * 
	 * @param request
	 * @return
	 */
	private boolean isAjaxRequest(HttpServletRequest request) {

		String requestedWith = request.getHeader("x-requested-with");
		// 表示是一个AJAX POST请求
		if ("XMLHttpRequest".equalsIgnoreCase(requestedWith)) {
			return true;
		}
		return false;
	}

//	/**
//	 * 处理菜单用户界面展示
//	 * @param menus
//	 * @param staff
//	 * @param topMenuId
//	 * @param session
//	 */
//	private void processMenus(List<MenuDisplayVO> menus, StaffInfoVo staff,HttpSession session){
//		if (menus != null && menus.size()>0) {
//			List<MenuDisplayVO> topMenus = new ArrayList<MenuDisplayVO>();
//			for (MenuDisplayVO menuVo : menus) {
//				//顶部菜单
//				MenuDisplayVO topMenu = new MenuDisplayVO();
//				topMenu.setMenuId(menuVo.getMenuId());
//
//				//左侧菜单
//				setAuthUrls(menuVo.getCatList(), staff, topMenu, session);
//				session.setAttribute("leftMenu_"+menuVo.getMenuId(), menuVo.getCatList());
//
//				if(staff.getAuthUrl() != null && staff.getAuthUrl().contains(menuVo.getMenuUrl())){
//					topMenu.setMenuUrl(menuVo.getMenuUrl());
//					topMenu.setMenuFullUrl(menuVo.getMenuFullUrl());
//				}
//				//添加top菜单
//				topMenu.setMenuTitle(menuVo.getMenuTitle());
//				topMenus.add(topMenu);
//			}
//			session.setAttribute("topMenu", topMenus);
//		} else {
//			session.removeAttribute("topMenu");
//			staff.setHasAuth(false);
//		}
//	}
//
//	/**
//	 * 递归获取菜单url
//	 * @param menus
//	 * @param staff
//	 * @param topMenuId
//	 * @param session
//	 */
//	private void setAuthUrls(List<MenuDisplayVO> menus, StaffInfoVo staff,MenuDisplayVO topMenu,HttpSession session) {
//
//		for (MenuDisplayVO vo : menus) {
//
//			if (StringUtils.isNotBlank(vo.getMenuUrl())) {
//				staff.getAuthUrl().add(vo.getMenuUrl());
//				session.setAttribute(vo.getMenuUrl(), topMenu.getMenuId());
//				//设置第一个菜单为top的连接
//				if(StringUtils.isBlank(topMenu.getMenuUrl()) == true){
//					topMenu.setMenuUrl(vo.getMenuUrl());
//					topMenu.setMenuFullUrl(vo.getMenuFullUrl());
//				}
//			}
//
//			// 目录不为空
//			if (vo.getCatList() != null && vo.getCatList().isEmpty() == false) {
//				setAuthUrls(vo.getCatList(), staff,topMenu,session);
//			}
//
//			// 子菜单不为空
//			if (vo.getMenuList() != null && vo.getMenuList().isEmpty() == false) {
//				setAuthUrls(vo.getMenuList(), staff,topMenu,session);
//			}
//		}
//	}
}
